package com.slfx.idgen.demo.idgen.customid;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.client.RestTemplate;

public class CachedCustomIdClient {
    private static long currentSequence = 0;
    private static long maxSequence = 0;
    private long step = 1;

    private static long nextCurrentSequence = 0;
    private static long nextMaxSequence = 0;

    private long threshold = 0;

    @Value("${spring.application.name}")
    private String appName;

    private String getNextStringId(String prefix) {
        return prefix + getNextId();
    }

    private long getNextId() {
//        if (currentSequence == threshold){
//            threadPoolExecutor.execute(()->{
//                getNextSequence();
//            });
//        }

        if (currentSequence + step > maxSequence) {
//            for (;;){
//                if (currentSequence < nextCurrentSequence) {
//                    threshold = (nextMaxSequence - nextCurrentSequence)/2+nextCurrentSequence;
//                    currentSequence = nextCurrentSequence;
//                    maxSequence = nextMaxSequence;
//                    break;
//                }
//            }
            getNextSequence();
        }
        currentSequence = currentSequence + step;
        return currentSequence;

    }

    private void getNextSequence() {
        String url = "http://localhost:8061/sequence/next/" + appName;
        RestTemplate restTemplate = new RestTemplate();
        Sequence sequence = restTemplate.getForObject(url, Sequence.class);
        maxSequence = sequence.getMaxSequence();
        currentSequence = sequence.getCurrentSequence();
    }


}
